﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace eTerm.Platform.Common
{
    public static class EnumHelper
    {
        public static string GetEnumName(Enum value) //where T:enum
        {
            StringBuilder sb = new StringBuilder();
            FlagsAttribute attr = Attribute.GetCustomAttribute(value.GetType(), typeof(FlagsAttribute)) as FlagsAttribute;
            if (attr == null)
            {
                return GetDescription(value);
            }
            int t = (int)Convert.ChangeType(value, typeof(int));
            //Enum x = (Enum)Convert.ChangeType(value, typeof(Enum));
            Enum.GetValues(value.GetType()).Cast<Enum>().ToList().ForEach(l => {
                Enum y = Convert.ChangeType(l, typeof(Enum)) as Enum;
                int x = (int)Convert.ChangeType(l, typeof(Enum));
                if ((t & x) != 0)
                {
                    string v = GetDescription(l);
                    if(!string.IsNullOrEmpty(v))
                        sb.AppendFormat(@"[{0}]", GetDescription(y));
                }
            });
            return sb.ToString();
        }


        /// <summary>
        /// 返回指定枚举值的描述（通过 
        /// <see cref="System.ComponentModel.DescriptionAttribute"/> 指定）。
        /// 如果没有指定描述，则返回枚举常数的名称，没有找到枚举常数则返回枚举值。
        /// </summary>
        /// <param name="value">要获取描述的枚举值。</param>
        /// <returns>指定枚举值的描述。</returns>
        public static string GetDescription(Enum value)
        {
            Type enumType = value.GetType();
            {
                MemberInfo[] mi = value.GetType().GetMember(value.ToString());
                if (mi != null && mi.Length > 0)
                {
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(mi[0], typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }
            return string.Empty;
        }
    }
}
